package com.example.dell.fastshopping.Trade;

import android.Manifest;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.example.dell.fastshopping.R;
import com.example.dell.fastshopping.order.OrderInfo;
import com.example.dell.fastshopping.order.OrderInfoActivity;
import com.example.dell.fastshopping.user.bank.BankCard;
import com.example.dell.fastshopping.utils.GlideUtils;
import com.example.dell.fastshopping.utils.KLog;
import com.example.dell.fastshopping.utils.ToastUtils;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 充值，支付
 */
public class TradeRechargeActivity extends AppCompatActivity {

    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.money)
    TextView money;
    @BindView(R.id.ensure_money)
    LinearLayout ensureMoney;
    @BindView(R.id.select_walit)
    ImageView selectWalit;
    @BindView(R.id.select_alipay)
    ImageView selectAlipay;
    @BindView(R.id.pay)
    TextView pay;
    @BindView(R.id.product_icon)
    ImageView productIcon;
    @BindView(R.id.oder_name)
    TextView oderName;
    @BindView(R.id.total_money)
    TextView totalMoney;

    LinearLayout itemOrderInfo;
    private String from;
    private int gradId;
    private String gradName;
    private TradeMoenyMolder molder;
    private String payType = "balancePay";//balancePay：余额支付  ；zfbPay：支付宝支付 ； wxPay：微信
    private static final int SDK_PAY_FLAG = 1;
    private MyHandle mHandler;
    private int marginId;
    private OrderInfo orderInfo;

    private static class MyHandle extends Handler {

        private final WeakReference<TradeRechargeActivity> reference;

        public MyHandle(TradeRechargeActivity tradeRechargeActivity) {
            reference = new WeakReference<>(tradeRechargeActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (reference.get() != null) {
                reference.get().receiveMessage(msg);
            }
        }
    }

    private void receiveMessage(Message msg) {
        PayResult payResult = new PayResult((Map<String, String>) msg.obj);
        /**
         * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
         */
        String resultInfo = payResult.getResult();// 同步返回需要验证的信息
        String resultStatus = payResult.getResultStatus();
        // 判断resultStatus 为9000则代表支付成功
        if (TextUtils.equals(resultStatus, "9000")) {
            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
            ToastUtils.showShort("支付成功");
            backForResult();
        } else if ("6001".equals(resultStatus)) {
            // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
            ToastUtils.showShort("用户取消");
        } else if ("5000".equals(resultStatus)) {

        } else {
            ToastUtils.showShort(payResult.getMemo());
        }
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_trade_recharge);
        ButterKnife.bind(this);
        itemOrderInfo = findViewById(R.id.item_order_info);
        initView();
    }

    private void initView() {

        requestPermission();

        mHandler = new MyHandle(this);
        Intent intent = getIntent();
        String hasMoney = intent.getStringExtra("money");
        money.setText("￥" + hasMoney);
        from = intent.getStringExtra("from");
        if ("ensureMoney".equals(from)) {
            ensureMoney.setVisibility(View.VISIBLE);
            itemOrderInfo.setVisibility(View.GONE);
            title.setText("保证金");
            gradId = intent.getIntExtra("gradId", -1);
            marginId = intent.getIntExtra("marginId", -1);
            gradName = intent.getStringExtra("gradName");

        } else if ("order".equals(from)) {
            ensureMoney.setVisibility(View.GONE);
            itemOrderInfo.setVisibility(View.VISIBLE);
            orderInfo = (OrderInfo) intent.getSerializableExtra("orderInfo");
            GlideUtils.setView(this, orderInfo.getPicString(), productIcon);
            oderName.setText(orderInfo.getProductName());
            totalMoney.setText(orderInfo.getTotalPriceString());
        }
        molder = ViewModelProviders.of(this).get(TradeMoenyMolder.class);

    }

    @OnClick({R.id.back, R.id.pay, R.id.select_walit, R.id.select_alipay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.pay:
                pay();
                break;
            case R.id.select_walit:
                selectWalit.setImageDrawable(getResources().getDrawable(R.mipmap.select));
                selectAlipay.setImageDrawable(getResources().getDrawable(R.mipmap.unselect));
                payType = "balancePay";
                break;
            case R.id.select_alipay:
                selectWalit.setImageDrawable(getResources().getDrawable(R.mipmap.unselect));
                selectAlipay.setImageDrawable(getResources().getDrawable(R.mipmap.select));
                payType = "zfbPay";
                break;
        }
    }

    private void pay() {
        if ("ensureMoney".equals(from)) {
            final HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("gradeId", gradId);
            hashMap.put("marginId", marginId);
            hashMap.put("gradeName", gradName);
            hashMap.put("payType", payType);

            molder.payEnsureMonery(hashMap).observe(this, new Observer<Object>() {
                @Override
                public void onChanged(@Nullable Object recharge) {
                    if ("zfbPay".equals(payType)) {
                        String s = new GsonBuilder().create().toJson(recharge);
                        Recharge recharge1 = new GsonBuilder().create().fromJson(s, Recharge.class);
                        zfbPlay(recharge1, "");
                    } else if ("balancePay".equals(payType)) {
                        ToastUtils.showShort("充值成功");
                        finish();
                    }
                }
            });
        } else if ("order".equals(from)) {
            HashMap<String, Object> hashMap = new HashMap<>();
            hashMap.put("orderId", orderInfo.getOrderId());
            hashMap.put("payType", payType);

            molder.payOrder(hashMap).observe(this, new Observer<String>() {
                @Override
                public void onChanged(@Nullable String json) {
                    KLog.e("3333333333");
                    if ("zfbPay".equals(payType)) {
                        zfbPlay(null, json);
                    } else if ("balancePay".equals(payType)) {
                        ToastUtils.showShort("充值成功");
                        backForResult();
                    }
                }
            });

        }
    }

    private void backForResult() {
        setResult(RESULT_OK);
        finish();
    }

    private void zfbPlay(Recharge recharge, String js) {
        final String json;
        if (recharge == null) {
            json = js;
        } else {
            json = recharge.getJson();
        }
        final Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(TradeRechargeActivity.this);
                Map<String, String> result = alipay.payV2(json, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    /**
     * 检查支付宝 SDK 所需的权限，并在必要的时候动态获取。
     * 在 targetSDK = 23 以上，READ_PHONE_STATE 和 WRITE_EXTERNAL_STORAGE 权限需要应用在运行时获取。
     * 如果接入支付宝 SDK 的应用 targetSdk 在 23 以下，可以省略这个步骤。
     */
    private static final int PERMISSIONS_REQUEST_CODE = 1002;

    private void requestPermission() {
// Here, thisActivity is the current activity
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this,
                    new String[]{
                            Manifest.permission.READ_PHONE_STATE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE
                    }, PERMISSIONS_REQUEST_CODE);

        }
    }

    /**
     * 权限获取回调
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUEST_CODE: {

                // 用户取消了权限弹窗
                if (grantResults.length == 0) {
                    ToastUtils.showShort("缺少权限，提现功能无法使用");
                    return;
                }

                // 用户拒绝了某些权限
                for (int x : grantResults) {
                    if (x == PackageManager.PERMISSION_DENIED) {
                        ToastUtils.showShort("缺少权限，提现功能将无法使用");
                        return;
                    }
                }
            }
        }
    }


}
